package com.cy.controller;

import com.cy.common.Constant;
import com.cy.entity.Event;
import com.cy.entity.User;
import com.cy.event.EventProducer;
import com.cy.service.LikeService;
import com.cy.util.CommunityUtil;
import com.cy.util.HostHolder;
import com.cy.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: cy
 * @Date: 2022/01/23/14:35
 * @Description:
 */
@Controller
public class LikeController {
    @Resource
    private HostHolder hostHolder;

    @Resource
    private LikeService likeService;

    @Resource
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping(path = "/like")
    @ResponseBody
    public String like(int entityType, int entityId, int entityUserId, int postId){
        User user = hostHolder.getUser();
        //点赞
        likeService.like(user.getId(), entityType, entityId, entityUserId);

        //获取点赞数量
        long likeCount = likeService.findEntityLikeCount(entityType, entityId);

        //查询某人对某实体的点赞状态  1代表点赞   0代表取消点赞
        int likeStatus = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);

        //返回的结果
        Map<String, Object> map = new HashMap<>();
        map.put("likeCount", likeCount);
        map.put("likeStatus", likeStatus);


        //发送点赞通知
        if(likeStatus == 1){
            //只有在当前状态是点赞时才去发送通知
            Event event = new Event();
            event.setTopic(Constant.TOPIC_LIKE);
            event.setUserId(hostHolder.getUser().getId());
            event.setEntityType(entityType);
            event.setEntityId(entityId);
            event.setEntityUserId(entityUserId);
            event.setData("postId", postId);

            eventProducer.fireMessage(event);
        }

        // 当对帖子进行点赞时才去计算得分
        if(entityType == Constant.ENTITY_TYPE_POST){
            redisTemplate.opsForSet().add(RedisKeyUtil.getPostScoreKey(), postId);
        }

        return CommunityUtil.getJsonString(0, null, map);
    }



}
